/*
	提供服务初始化，包括数据库，Redis，Mq，日志文件等
*/
package initialize

import (
	"fmt"
	"github.com/go-redis/redis/v7"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	_ "github.com/lib/pq"
	"log"
)

var (
	PgDb           *gorm.DB           //数据库客户端
	RedisClient    *redis.Client      //redis单机客户端
	Config         *viper.Viper       //全局配置
)

//	提供系统初始化，全局变量
func Init(config *viper.Viper) {

	Config = config
	var err error

	//postPG配置
	pgArgs := LoadPGArgs()
	dbConf := LoadDatabaseConfig()
	db, err := gorm.Open("postgres", pgArgs)
	if err != nil {
		log.Fatal(err)
	}
	db.DB().SetMaxOpenConns(dbConf.MaxOpenConns)
	db.DB().SetMaxIdleConns(dbConf.MaxIdleConns)
	PgDb = db
	// 激活链接
	if err = PgDb.DB().Ping(); err != nil {
		panic(err)
	}

	//	Redis客户端
	RedisClient = redis.NewClient(&redis.Options{
		Addr:     config.GetString("Redis.default.addr"),
		Password: config.GetString("Redis.default.password"), // no password set
		DB:       config.GetInt("Redis.default.db"),  // use default DB
	})
	err = RedisClient.Ping().Err()
	if err != nil {
		panic(err)
	}

}

func LoadPGArgs() string {
	dbConfig := LoadDatabaseConfig()
	args := fmt.Sprintf(
		"sslmode=disable host=%s port=%d user=%s password='%s' dbname=%s timezone='Asia/Shanghai'",
		dbConfig.Host,
		dbConfig.Port,
		dbConfig.User,
		dbConfig.Password,
		dbConfig.DatabaseName,
	)
	return args
}
func LoadDatabaseConfig() *DatabaseConfig {
	dbConfig := &DatabaseConfig{
		Host:         Config.GetString("db.host"),
		Port:         Config.GetInt("db.port"),
		User:         Config.GetString("db.user"),
		Password:     Config.GetString("db.password"),
		DatabaseName: Config.GetString("db.dbname"),
		MaxIdleConns: Config.GetInt("db.max_idle_conn"),
		MaxOpenConns: Config.GetInt("db.max_open_conn"),
	}
	return dbConfig
}

type DatabaseConfig struct {
	Host         string
	Port         int
	User         string
	Password     string
	DatabaseName string
	MaxIdleConns int
	MaxOpenConns int
}
